package com.guigu.tms.dispatch.service.impl;

import com.guigu.tms.commons.aggregation.entity.*;
import com.guigu.tms.commons.aggregation.feign.TransportTripsFeignClient;
import com.guigu.tms.commons.dispatch.entity.CacheLineDetail;
import com.guigu.tms.commons.dispatch.entity.OrderClassify;
import com.guigu.tms.commons.dispatch.entity.OrderClassifyAttach;
import com.guigu.tms.dispatch.dto.OrderLineSimpleDTO;
import com.guigu.tms.dispatch.dto.OrderLineTripsTruckDriverDTO;
import com.guigu.tms.dispatch.service.IOrderClassifyAttachService;
import com.guigu.tms.dispatch.service.ITaskTripsSchedulingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskTripsSchedulingServiceImpl implements ITaskTripsSchedulingService {

   @Autowired
   private TransportTripsFeignClient transportTripsFeignClient;

   @Autowired
   private IOrderClassifyAttachService orderClassifyAttachService;

    @Override
    public List<OrderLineTripsTruckDriverDTO> execute(List<OrderLineSimpleDTO> orderLineSimpleDTOS, String agencyId, String jobId, String logId, String params) {
        List<OrderLineTripsTruckDriverDTO> orderLineTripsTruckDrivers=new ArrayList<>();
        orderLineSimpleDTOS.forEach(item->{
            CacheLineDetail cacheLineDetail = item.getCacheLineDetail();
            //根据线路编号获取车次
            List<TransportTrips> transportTrips=transportTripsFeignClient.getTransportTrips(cacheLineDetail.getTransportLineId());
            if(CollectionUtils.isEmpty(transportTrips)){
                return;
            }
            // 根据车次编号获取车次关联信息
            List<String> tripsIds=transportTrips.stream().map(item1->item1.getTransportTripsId().toString()).collect(Collectors.toList());
            List<TransportTripsTruckDriver> transportTripsTruckDrivers=transportTripsFeignClient.getTripsTruckDriver(tripsIds);
            if (CollectionUtils.isEmpty(transportTripsTruckDrivers)) {
                return;
            }
            // 可用车次列表 遍历集合  一个车次会有多个车和司机，获取状态正常的车次
            List<TransportTripsTruckDriver> transportTripsTruckDrivers1= getTripsTruckDriver(transportTripsTruckDrivers);;
            if (CollectionUtils.isEmpty(transportTripsTruckDrivers1)) {
                return;
            }

            //遍历全部可用车次 根据时间匹配车次 （根据车次发车时间（小时：分钟）与当前时间比较，最近发车的车次作为最优方案）
            TransportTripsTruckDriver tripsTruckDriver=getBestTripsTruckDriver(transportTripsTruckDrivers1);
            if(tripsTruckDriver==null){
                return;
            }
            //保存
            save(tripsTruckDriver,item.getOrderClassifys());

            orderLineTripsTruckDrivers.add(new OrderLineTripsTruckDriverDTO(tripsTruckDriver, cacheLineDetail.getTransportLineId(),item.getOrderClassifys() ));
        });

        return orderLineTripsTruckDrivers;
    }
    //保存 订单分类 车次，车辆，司机关联信息
    private void save(TransportTripsTruckDriver tripsTruckDriver, List<OrderClassify> orderClassifys) {
        for (OrderClassify orderClassify : orderClassifys) {
            com.guigu.tms.commons.dispatch.entity.OrderClassifyAttach orderClassifyAttach = new OrderClassifyAttach();
            orderClassifyAttach.setOrderClassifyId(orderClassify.getId());
            orderClassifyAttach.setTripsId(tripsTruckDriver.getTransportTripsId());
            orderClassifyAttach.setTruckId(tripsTruckDriver.getTruckId());
            orderClassifyAttach.setDriverId(tripsTruckDriver.getUserId());
            orderClassifyAttachService.save(orderClassifyAttach);
        }
    }

    //获取最优车次
    private TransportTripsTruckDriver getBestTripsTruckDriver(List<TransportTripsTruckDriver> transportTripsTruckDrivers) {

        TransportTripsTruckDriver tripsTruckDriver=null;
        //获取所有车次编号
        List<String> tripsIds=transportTripsTruckDrivers.stream().map(item->item.getTransportTripsId()).collect(Collectors.toList());
        //查询车次信息
        List<TransportTrips> transportTrips=transportTripsFeignClient.getTransportTripsByIds(tripsIds);
        //按照发车时间先后排序
        transportTrips=transportTrips.stream().sorted(Comparator.comparing(TransportTrips::getDepartureTime)).collect(Collectors.toList());

        List<TransportTrips> trips=new ArrayList<>();
        //当前时间
        LocalTime nowTime = LocalTime.now();
        transportTrips.forEach(transportTrip->{
            List<Integer> t= Arrays.stream(transportTrip.getDepartureTime().split(":")).map(item->Integer.parseInt(item)).collect(Collectors.toList());
            //发车时间
            LocalTime time = LocalTime.of(t.get(0), t.get(1));
            //发车时间与当前时间差
            long seconds = Duration.between(nowTime, time).toMinutes();
            if(seconds>0){
                transportTrip.setBetweenTime(seconds);
                trips.add(transportTrip);
            }
        });

        if(CollectionUtils.isEmpty(trips)){
            return null;
        }
        TransportTrips trips1 = trips.stream().sorted(Comparator.comparing(TransportTrips::getBetweenTime)).collect(Collectors.toList()).get(0);
        tripsTruckDriver=transportTripsTruckDrivers.stream().filter(item->item.getTransportTripsId().equals(trips1.getTransportTripsId())).collect(Collectors.toList()).get(0);

        return tripsTruckDriver;
    }


    /**
     * 获取全部可以用车次 车辆 司机
     *
     * @param transportTripsTruckDrivers
     * @return
     */
    private List<TransportTripsTruckDriver> getTripsTruckDriver(List<TransportTripsTruckDriver> transportTripsTruckDrivers) {

        //根据车次编号分组
        Map<String, List<TransportTripsTruckDriver>> transportTripsTruckDriverMap = transportTripsTruckDrivers.stream().collect(Collectors.groupingBy(TransportTripsTruckDriver::getTransportTripsId));

        List<TransportTripsTruckDriver> tripsTruckDrivers = new ArrayList<>();
        transportTripsTruckDriverMap.forEach((transportTripsId,transportTripsTruckDriverList)->{

            // 获取全部车辆
            List<String> truckIds=transportTripsTruckDriverList.stream().filter(item->item!=null).map(item->item.getTruckId()).collect(Collectors.toList());
            List<Truck> trucks=transportTripsFeignClient.getTruckByIds(truckIds);
            // 获取状态正常的车辆id
            List<String> trucks1=trucks.stream().filter(item->item.getStatus()==1).map(item->item.getTruckId().toString()).collect(Collectors.toList());

            // 获取可用司机
            List<String> drivers=transportTripsTruckDriverList.stream().filter(item->item.getUserId()!=null).map(item->item.getUserId()).collect(Collectors.toList());

            // 可用车次 车辆  司机  添加到模型中
            transportTripsTruckDriverList.forEach(item->{
                if(trucks1.contains(item.getTruckId())&&drivers.contains(item.getUserId())){
                    tripsTruckDrivers.add(item);
                }
            });
        });

        return tripsTruckDrivers;
    }
}
